import { h, defineComponent } from 'vue'
import type {
  Plugin,
  PluginConfig,
  PluginComponent,
  PluginManagerConfig,
  VirtualComponent
} from './types'
import { fetchRemoteComponents } from './mock/remoteComponents'

class PluginManager {
  private plugins: Map<string, Plugin> = new Map()
  private config: PluginManagerConfig = {
    allowVirtual: true,
    validateMetadata: true
  }

  constructor(config?: Partial<PluginManagerConfig>) {
    if (config) {
      this.config = { ...this.config, ...config }
    }
  }

  // 注册插件
  async register(plugin: Plugin): Promise<void> {
    try {
      // 验证插件配置
      if (!plugin.config || !plugin.config.name) {
        throw new Error('Invalid plugin configuration')
      }

      // 验证组件元数据
      if (this.config.validateMetadata) {
        for (const component of plugin.config.components) {
          if (!component.metadata || !component.metadata.type || !component.metadata.category) {
            throw new Error(`Invalid component metadata in plugin ${plugin.config.name}`)
          }
        }
      }

      // 如果不允许虚拟组件，检查是否包含虚拟组件
      if (!this.config.allowVirtual) {
        const hasVirtual = plugin.config.components.some(c => c.virtual)
        if (hasVirtual) {
          throw new Error(`Virtual components are not allowed in plugin ${plugin.config.name}`)
        }
      }

      // 执行插件的setup函数
      if (plugin.setup) {
        await plugin.setup()
      }

      // 注册插件
      this.plugins.set(plugin.config.name, plugin)
    } catch (error) {
      if (this.config.onError) {
        this.config.onError(error as Error)
      }
      throw error
    }
  }

  // 卸载插件
  async unregister(pluginName: string): Promise<void> {
    const plugin = this.plugins.get(pluginName)
    if (plugin) {
      if (plugin.destroy) {
        await plugin.destroy()
      }
      this.plugins.delete(pluginName)
    }
  }

  // 获取插件
  getPlugin(pluginName: string): Plugin | undefined {
    return this.plugins.get(pluginName)
  }

  // 获取所有插件
  getAllPlugins(): Plugin[] {
    return Array.from(this.plugins.values())
  }

  // 获取所有组件
  getAllComponents(): PluginComponent[] {
    const components: PluginComponent[] = []
    this.plugins.forEach(plugin => {
      components.push(...plugin.config.components)
    })
    return components
  }

  // 加载远程组件
  async loadRemoteComponents(): Promise<void> {
    try {
      const remotePlugin = await fetchRemoteComponents()
      await this.register(remotePlugin)
    } catch (error) {
      if (this.config.onError) {
        this.config.onError(error as Error)
      }
      throw error
    }
  }
}

// 创建单例实例
export const pluginManager = new PluginManager()

export default PluginManager 